import axios from "axios";
import { message } from "ant-design-vue";
const baseURL = "https://www.tjyzsz.com";

const ContentType = {
  urlencoded: "application/x-www-form-urlencoded;charset=UTF-8",
  json: "application/json",
  formData: "multipart/form-data",
};

// 创建 axios 实例
const baseService = axios.create({
  baseURL: "/api/",
  timeout: 20000,
});

// request interceptor
baseService.interceptors.request.use(
  (config) => {
    config.headers["Content-Type"] =
      ContentType[config.data instanceof FormData ? "formData" : "json"];
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 处理响应错误的函数
const handleResponseError = (error) => {
  const { response, message: msg } = error;

  if (response) {
    const { data, code } = response; // 使用 code 代替 code
    if (data?.msg) {
      message.error(data.msg);
    } else {
      switch (code) {
        case 401:
        case 403:
          message.error("登录过期或权限不足, 请重新登陆!");
          emitter.emit("axios_goto_login");
          break;
        case 500:
          message.error("请求数据失败, 请重试!");
          break;
        case 406:
          message.error("登陆超时请重新登录!");
          emitter.emit("axios_goto_login");
          break;
        default:
          message.error("未知错误,请重试!");
      }
    }
  } else if (msg) {
    message.error(msg === "Network Error" ? "网络错误,请检查网络!" : msg);
  } else if (!error.__CANCEL__) {
    message.error("未知错误,请重试!");
  }
  return false;
};

baseService.interceptors.response.use(
  (res) => {
    console.log("请求返回！");
    if (res.data.code === 200) {
      // 使用 code 代替 code
      return res.data;
    } else if (res.data.code === 401) {
      message.error(res.data.code);
    }
    return res;
  },
  handleResponseError // 使用提取的错误处理函数
);

export { baseService, baseURL };
